package com.aacar.op.service.order;


import com.aacar.op.dao.mem.MemDao;
import com.aacar.op.dao.order.OrderDao;
import com.aacar.op.entity.mem.Member;
import com.aacar.op.entity.order.Order;
import com.aacar.op.entity.sms.SmsDto;
import com.aacar.op.utils.DefineAppConfig;
import com.aacar.op.utils.MathUtil;
import com.aacar.op.utils.message.SmSUtils;
import com.aacar.op.utils.web.PageUtils;
import com.alibaba.fastjson.JSON;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import push.PushUtils;

import java.util.List;
import java.util.Map;

//import push.PushUtils;

@Service("orderService")
@Transactional
public class OrderServiceImpl implements OrderService {
	
	private static Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);
	
    @Autowired
    private OrderDao orderDao;

	@Autowired
	private MemDao memDao;

	@Override
	public Order get(String order) {

		return null;
	}


	@Override
	public int saveOrUpdate(Order entity) {
	    int res = 0;
        logger.info("##################### orderStatus:"+entity.getOrderStatus());
        logger.info("##################### orderNo:"+entity.getOrderNo());
        logger.info("##################### userId:"+entity.getUserId());
        logger.info("##################### refundStatus:"+entity.getRefundStatus());
        Member member = memDao.findOne(Long.valueOf(entity.getUserId()));
		entity.auditObject();
        Order orderRes = orderDao.findOrder(entity.getOrderNo());
		if ("".equals(entity.getOrderNo())||entity.getOrderNo()==null) {
			//to do
		} else {
			//接单操作
			if("R03".equals(entity.getOrderStatus())){
                if("R02".equals(orderRes.getOrderStatus()) ) { //等待接单
                    entity.setOrderStatusName("已接单");
                    entity.setOrderSubStatus("R0302");
                    orderDao.update(entity);
                    //修改需求订单
                    entity.setDemandStatus("DE03");
                    entity.setDemandSubStatus("DE0302");
                    orderDao.updateOrderDemand(entity);
                    //推送消息
                    PushUtils.sendAndroidAndIOSUnicast(member.getDeviceType(), member.getDeviceTokens(), "您尾号为" + entity.getOrderNo().substring(16) + "的订单(已接单)", entity.getOrderNo());

                    //发短信 (短信模型已接单)
                    try {
                        SmsDto smsDto = new SmsDto();
                        smsDto.setOrderNo(entity.getOrderNo().substring(16));
                        SendSmsResponse response = SmSUtils.sendSms(member.getPhoneNo(), DefineAppConfig.OrderMessage_SMS_Template, JSON.toJSONString(smsDto));
                        logger.info("发送短信返回值为:code:" + response.getCode() + "===message:" + response.getMessage());
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }else{
                    res = 500;
                }
			}else if("R08".equals(entity.getOrderStatus())){ //取消订单

                //只有在R01-待支付 R02-等待接单 R03-已接单 才可以操作取消
                if ("R01".equals(orderRes.getOrderStatus()) || "R02".equals(orderRes.getOrderStatus())|| "R03".equals(orderRes.getOrderStatus())) {
                    //修改主订单
                    entity.setOrderStatusName("已取消");
                    entity.setOrderSubStatus("R08");
                    orderDao.update(entity);

                    //修改需求订单
                    entity.setDemandStatus("DE04");
                    entity.setDemandSubStatus("DE0402");
                    orderDao.updateOrderDemand(entity);

                    if ("R02".equals(orderRes.getOrderStatus())||"R03".equals(orderRes.getOrderStatus())){//只有在已支付的时候 取消 才有退款记录
                        //修改支付订单状态 记录退款金额 退款状态
                        if (orderRes.getPayAmount() != 0 && orderRes.getThirdPayCallBackStr()!=null) {
                            entity.setRefundAmount(orderRes.getPayAmount());
                            entity.setRefundStatus("1"); //待退款
                        }
                    }

                    entity.setPayStatus("PA03");
                    entity.setPayStatus("PA0302");
                    orderDao.updateOrderPay(entity);

                    //退还积分
                    if (orderRes.getPayIntegral() != 0) {
                        entity.setUserId(entity.getUserId());
                        entity.setIntegral(MathUtil.disposeAmount(-orderRes.getPayIntegral()));
                        orderDao.updateMember(entity);

                        //插入会员积分记录
                        entity.setIntegralRecordstype("3");
                        entity.setPayIntegral(orderRes.getPayIntegral());
                        orderDao.insertIntegralRecords(entity);
                    }

                    //退还优惠券
                    if (orderRes.getCouponNo()!=null&&!"".equals(orderRes.getCouponNo())) {
                        entity.setCouponNo(orderRes.getCouponNo());
                        entity.setCouponStatus("1"); //优惠券状态 2-已使用
                        entity.setCouponFlag("1"); //0-无效
                        orderDao.updateCoupon(entity);
                    }

                    //只有下单时为银牌会员  退换首单 查询该订单对应的用户是否有除了取消以外的订单 如果有 不退首单状态
                    if("2".equals(orderRes.getUserRankId())) {
                        int notCancelOrderCount = orderDao.findNotCancelCount(Long.valueOf(orderRes.getUserId()));
                        if (notCancelOrderCount == 0) {
                            //退首单状态
                            Order param = new Order();
                            param.setUserId(entity.getUserId());
                            param.setIsFirstOrder("1");
                            orderDao.updateMember(param);

                        }
                    }



                    //推送消息
                    PushUtils.sendAndroidAndIOSUnicast(member.getDeviceType(), member.getDeviceTokens(), "您尾号为" + entity.getOrderNo().substring(16) + "的订单(已取消)", entity.getOrderNo());

                }else{
                    res = 100;
                }
            }else if("R04".equals(entity.getOrderStatus())) { //开始洗车操作
                if("R03".equals(orderRes.getOrderStatus()) ) {
                    //更新主订单状态为洗车中
                    entity.setOrderStatusName("洗车中");
                    entity.setOrderSubStatus("R04");
                    orderDao.update(entity);
                    //推送消息
                    PushUtils.sendAndroidAndIOSUnicast(member.getDeviceType(), member.getDeviceTokens(), "您尾号为" + entity.getOrderNo().substring(16) + "的订单(洗车中)", entity.getOrderNo());
                }else{
                    res = 200;
                }
            }else if("R06".equals(entity.getOrderStatus())) { //操作完成
                if("R04".equals(orderRes.getOrderStatus()) ) {
                    entity.setOrderStatusName("已完成");
                    entity.setOrderSubStatus("R06");
                    orderDao.update(entity);

                    PushUtils.sendAndroidAndIOSUnicast(member.getDeviceType(), member.getDeviceTokens(), "您尾号为" + entity.getOrderNo().substring(16) + "的订单(已完成)", entity.getOrderNo());
                }else{
                    res = 300;
                }
            }else if("2".equals(entity.getRefundStatus())){ //退款操作
                if("1".equals(orderRes.getRefundStatus())) {
                    //更新支付订单为已退款
                    orderDao.updateOrderPay(entity);
                    PushUtils.sendAndroidAndIOSUnicast(member.getDeviceType(), member.getDeviceTokens(), "您尾号为" + entity.getOrderNo().substring(16) + "的订单(已退款)", entity.getOrderNo());
                }else{
                    res = 400;
                }
            }


		}
		return res;
	}

	@Override
	public int delete(String  orderNo) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public PageInfo<Order> getPage(Map<String, Object> params, Pageable pageable) {
		PageUtils.mergeSort(params, pageable);
        //pageNum(页码)从1开始,spring data common domain从0开始的.
        PageHelper.startPage(pageable.getPageNumber() + 1, pageable.getPageSize());
        List<Order> pageContent = orderDao.findAll(params);
        return new PageInfo(pageContent);
	}




}
